import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$rootScope', '$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api', 'MetaFieldService')
export class MetaModelList {
	constructor($rootScope, $scope, $state, dialog, http, api, service) {
		var appScope = $scope.$parent;

		function getTreeNode() {
			return appScope.getTreeNode();
		}

		var _node = getTreeNode();
		if (!_node) {
			appScope.select('meta.model.info');
			return;
		}

		// 初始化检索
		var q = $scope.q = {};

		var loadData = $scope.loadData = function(params) {
			var node = getTreeNode();
			if (!node) return;
			params = params || {};
			angular.extend(params, {
				id: node.id
			})

			api.gridLoad({
				name: 'meta_models',
				params: params,
				scope: $scope
			});
		};

		var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		function treeReload() {
			appScope.treeReload();
		}

		var dataTypes = service.dataTypes,
			formTypes = service.formTypes;

		$scope.gridOptions = {
			showHeader: false,
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			paginationTemplate: 'grid/ui-paging',
			dataView: {
				rowTemplate: '<div class="ui-grid-item-body"><div class="ui-item-ico"><i class="fa fa-table"></i></div><div class="ui-item-text">{{grid.getRowValue(row, \'cubeNameCn\')}}</div></div>',
				tools: [{
					icoCls: 'edit',
					title: '修改'
				}, {
					icoCls: 'download',
					title: '生成样例'
				}, {
					name: 'fieldsManager',
					title: '指标管理',
					icoCls: 'th-large'
				}, {
					name: 'remove',
					icoCls: 'trash-o',
					title: '删除'
				}]
			},
			// paginationCurrentPage: api.page.pageNumber,
			// paginationPageSize: api.page.pageSize,
			// useExternalPagination: true,
			// columns: [{
			// 	name: '序号',
			// 	width: 50,
			// 	cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
			// }, {
			// 	name: '目录名称',
			// 	field: 'name',
			// 	width: 150
			// }, {
			// 	name: '备注',
			// 	align: 'left',
			// 	field: 'desc'
			// }],
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}
		};

		$scope.add = function(appScope) {
			appScope = appScope || this;
			var node = appScope.getTreeNode();
			var id = node.id;
			api.form({
				title: '新建虚拟表',
				template: require('../views/form_model.tpl.html'),
				name: 'meta_model_add',
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'radio',
						url: 'category/treeClass',
						params: {
							mid: id
						}
					});
				},
				beforeSubmit: function(data) {
					var _scope = this;

					data.parentid = api.getTreeChecked(_scope.tree).map(function(node) {
						return node.id
					})[0];
				},
				resolveWait: {
					options: function() {
						return http.post({
							name: 'meta_model_options'
						});
					}
				},
				resolveApplyScope: true
			}).then(function() {
				treeReload();
			});
		}

		$scope.edit = function(ev, id) {
			id = typeof id == 'undefined' ? api.getGridSelectedId($scope) : id;

			api.form({
				title: '修改虚拟表',
				template: require('../views/form_model.tpl.html'),
				name: 'meta_model_edit',
				beforeSettings: function() {
					var _scope = this;
					api.tree({
						scope: _scope,
						type: 'radio',
						url: 'category/treeClass',
						params: {
							eid: id
						}
					});
				},
				beforeSubmit: function(data) {
					var _scope = this;

					data.parentid = api.getTreeChecked(_scope.tree).map(function(node) {
						return node.id
					})[0];
				},
				resolveWait: {
					options: function() {
						return http.post({
							name: 'meta_model_options'
						});
					},
					model: function() {
						return http.post({
							name: 'meta_model',
							params: {
								id: id
							}
						});
					}
				},
				resolveApplyScope: ['options'],
				resolveApplyData: ['model']
			}).then(function() {
				query();
			});
		}
		$scope.remove = function(ev, id) {
			id = typeof id == 'undefined' ? api.getGridSelectedId($scope) : id;

			dialog.confirm('确定要删除选中项？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'meta_model_remove',
						params: {
							id: id
						},
						success: function() {
							treeReload();
						}
					})
				}
			});
		}

		$scope.download = function(ev, id) {
			$rootScope.download('cube/exportExcel?id=' + id);
		}

		$scope.expExcel = function(ev, ids) {
			ids = typeof ids == 'undefined' ? api.getGridSelectedIds($scope) : ids;
			$rootScope.download('cube/download?ids=' + ids);
		}


		$scope.order = function() {
			var id = api.getGridSelectedId($scope);

			api.form({
				title: '调整顺序',
				template: require('../views/form_model_order.tpl.html'),
				resolveWait: http.post({
					name: 'meta_model_order_desc',
					params: {
						id: id
					}
				}),
				config: {
					windowClass: 'x-window',
					width: 640
				}
			})
		}

		$scope.fieldsManager = function(ev, id) {
			id = typeof id == 'undefined' ? api.getGridSelectedId($scope) : id;

			var loadModelFieldsData = function(scope, params) {
				scope = scope || this;
				params = params || {};
				angular.extend(params, {
					modelId: id
				});
				return api.gridLoad({
					name: 'meta_model_fields',
					params: params,
					scope: scope
				});
			};
			api.form({
				title: '指标管理',
				template: require('../views/form_model_fields.tpl.html'),
				scope: {
					q: {},
					getDataTypeName: service.getDataTypeName,
					setRules: function(grid, row, rules) {
						var _scope = this;
						var _id = grid.getRowValue(row, 'id');
						var loadRulesData = function(scope, params) {
							params = params || {};
							angular.extend(params, {
								ruleType: '1'
							});
							return api.gridLoad({
								name: 'meta_rules',
								params: params,
								scope: scope || this
							});
						};
						api.form({
							title: '选择检验规则',
							template: require('../views/form_rules.tpl.html'),
							name: 'meta_rules_add',
							data: {
								modelId: id,
								id: _id
							},
							beforeSubmit: function(data, deferred) {
								var _scope = this;
								var _data = _scope.gridBufferOptions.data || [];
								var rows = _data.map(function(r) {
									return {
										id: r.id,
										value: r.value
									}
								});
								/*if (rows.length === 0) {
									dialog.alert('请选取需要导入的数据！');
									return false;
								}*/
								data.rows = rows;
							},
							scope: {
								q: {},
								query: function(resetPage) {
									var scope = this;
									if (resetPage === false || scope.gridOptions.paginationCurrentPage == 1) {
										loadRulesData(scope, scope.q);
									} else {
										api.gridReset(null, scope);
									}
								},
								hasSelectedRecords: function(apiName) {
									return api.hasGridSelectedRecords(this, apiName);
								},
								gridOptions: {
									paginationCurrentPage: api.page.pageNumber,
									paginationPageSize: api.page.pageSize,
									useExternalPagination: true,
									columns: [{
											name: '序号',
											width: 50,
											cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
										}, {
											name: '规则名称',
											align: 'left',
											width: 200,
											field: 'ruleName'
										}
										/*, {
																			name: '规则属性',
																			width: 200,
																			align: 'left',
																			field: 'value',
																			cellTemplate: '<div class="x-grid-inner" ng-if="!row.isSelected">{{grid.getCellValue(row, col)}}</div><div class="x-form-inner" ng-if="row.isSelected"><input class="x-ipt" type="text" ng-model="row.entity.value" ng-click="$event.stopPropagation()" required /></div>'
																		}*/
										, {
											name: '描述',
											width: 200,
											field: 'ruleDesc'
										}
									],
									forceFit: false,
									onRegisterApi: function(api, grid) {
										var scope = grid.appScope;
										scope.api = api;

										api.pagination && api.pagination.on.paginationChanged(scope, function(newPage, pageSize) {
											scope.query(false);
										});
									}
								},
								add: function() {
									var _scope = this;
									//								if (!_scope.form.$valid) {
									//									_scope.form.$setSubmitted();
									//									return;
									//								}
									// 								var rs = api.getGridSelectedRecords(_scope);
									// 								var _data = _scope.gridBufferOptions.data || [];
									// 								var ids = _data.map(function(_r) {
									// 									return _r.id;
									// 								});
									// 								var data = [];
									// 								rs.forEach(function(r) {
									// 									var id = r.id;
									// 									if (ids.indexOf(id) === -1) {
									// 										if (r.$$hashKey) {
									// 											delete r.$$hashKey;
									// 										}
									// 										data.push(r);
									// 									}
									// 								});
									// 								_scope.gridBufferOptions.data = [].concat(_data, data);
									var _data = _scope.gridBufferOptions.data || [];
									var ids = _data.map(function(_r) {
										return _r.id;
									});

									var _add = function(data) {
										var i;
										if ((i = ids.indexOf(data.id)) === -1) {
											_scope.gridBufferOptions.data = [].concat(_data, data);
										} else {
											dialog.confirm('当前规则已在配置列表中，是否覆盖已有配置？').result.then(function(r) {
												if (r) {
													_scope.gridBufferOptions.data.splice(i, 1, data);
												}
											});
										}
									}

									var data = api.getGridSelectedRecord(_scope);
									var hasParams = data.noParams !== true;
									if (hasParams) {
										api.form({
											title: '规则配置',
											template: require('../views/form_rule_params.tpl.html'),
											data: data
										}).then(function(data) {
											_add(data);
										});
									} else {
										_add(data);
									}
								},
								edit: function(grid, row) {
									var _scope = this;
									var data = grid.getData(row);
									var id = data.id;
									var _data = _scope.gridBufferOptions.data || [];
									var ids = _data.map(function(_r) {
										return _r.id;
									});
									var i = ids.indexOf(id);
									api.form({
										title: '规则配置',
										template: require('../views/form_rule_params.tpl.html'),
										data: data
									}).then(function(data) {
										_scope.gridBufferOptions.data.splice(i, 1, data);
									});
								},
								remove: function() {
									var _scope = this;
									var data = _scope.gridBufferOptions.data || [];
									var rs = api.getGridSelectedRecords(_scope, 'bufferApi');
									rs.forEach(function(r) {
										var id = r.id,
											i;
										var ids = data.map(function(_r) {
											return _r.id;
										});
										if ((i = ids.indexOf(id)) !== -1) {
											data.splice(i, 1);
											_scope.bufferApi.selections.removeKey(id);
											_scope.bufferApi.grid.selection.selectedCount--;
										}
									});
								},
								gridBufferOptions: {
									enableFullRowSelection: false,
									columns: [{
											name: '序号',
											width: 50,
											cellTemplate: '<div class="x-grid-inner">{{index + 1}}</div>'
										}, {
											name: '规则名称',
											align: 'left',
											width: 200,
											field: 'ruleName'
										}
										/*, {
																			name: '规则属性',
																			width: 200,
																			align: 'left',
																			field: 'value',
																			cellTemplate: '<div class="x-grid-inner" ng-if="!row.editable" ng-click="row.editable=true">{{grid.getCellValue(row, col)}}</div><div class="x-form-inner" ng-if="row.editable"><input type="text" ng-model="row.entity.value" required ng-blur="row.editable=false" auto-focus="row.editable" /></div>'
																		}*/
										, {
											name: '描述',
											width: 200,
											field: 'ruleDesc'
										}, {
											name: '操作',
											width: 200,
											cellTemplate: '<span class="btn-label" ng-if="grid.getData(row).noParams!=true" ng-click="grid.appScope.edit(grid, row)">修改</span>'
										}
									],
									forceFit: false,
									onRegisterApi: function(bufferApi, grid) {
										var scope = grid.appScope;
										scope.bufferApi = bufferApi;

										if (bufferApi.selection) {
											grid.registerDataChangeCallback(function() {
												var visibleRows = bufferApi.core.getVisibleRows();
												grid.selection.selectAll = visibleRows.length > 0 && bufferApi.selection.getSelectedCount() === visibleRows.length;
											}, ['row']);
										}
									}
								}
							},
							resolveApply: false,
							resolveWait: function() {
								var _scope = this;
								return {
									grid: function() {
										return loadRulesData(_scope);
									},
									gridBuffer: function() {
										return api.gridLoad({
											name: 'meta_rules_filter',
											params: {
												modelId: id,
												id: _id
											},
											options: 'gridBufferOptions',
											apiName: 'bufferApi',
											scope: _scope
										});
									}
								}
							},
							config: {
								width: 760
							}
						}).then(function() {
							_scope.query(false);
						});
					},
					setFieldUnique: function(grid, row, value) {
						var metricId = grid.getRowValue(row, 'id');

						row.uniqueLoading = true;
						http.post({
							name: 'meta_field_unique',
							params: {
								cubeId: id,
								metricId: metricId,
								value: value
							}
						}).finally(function() {
							row.uniqueLoading = false;
						});
					},
					gridOptions: {
						paginationCurrentPage: api.page.pageNumber,
						paginationPageSize: api.page.pageSize,
						useExternalPagination: true,
						viewportTemplate: '<div class="x-grid-wrap">\
							<div class="x-grid-body">\
								<table cellspacing="0" cellpadding="0">\
									<tbody>\
										<tr ng-repeat="(rowIndex, row) in grid.renderedRows track by $index" ng-class="{\'x-grid-row-selected\':row.isSelected, \'x-grid-row-disabled\': row.enableSelection === false}">\
												<td class="x-grid-group">\
													<table cellspacing="0" cellpadding="0">\
														<tbody>\
															<tr row="row" index="rowIndex" grid-view-row></tr>\
														</tbody>\
													</table>\
													<div class="x-field-group" ng-if="grid.getRowValue(row, \'inRules\').length > 0">\
														<div class="x-field">\
															<div class="x-field-header">\
																<h4><label><i class="fa fa-info-circle"></i> 规则列表</label></h4>\
															</div>\
															<div class="x-field-body">\
																<div class="x-grid-list-inner">\
																	<ul>\
																		<li ng-repeat="rule in grid.getRowValue(row, \'inRules\') track by $index">{{rule.ruleName}}：<span class="text-danger">{{rule.value}}</span></li>\
																	</ul>\
																</div>\
															</div>\
														</div>\
													</div>\
												</td>\
											</tr>\
										</tbody>\
									</table>\
								</div>\
							</div>',
						rowClass: function(row, data) {
							if (data.metricType == 'D') {
								row.enableSelection = false;
							}
						},
						columns: [{
							name: '序号',
							width: 50,
							cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
						}, {
							name: '指标名称',
							field: 'metricCode',
							width: 200
						}, {
							name: '显示名称',
							width: 200,
							field: 'metricName'
						}, {
							name: '数据类型',
							field: 'fieldType',
							width: 150,
							cellTemplate: '<div class="x-grid-inner">{{grid.appScope.getDataTypeName(grid.getCellValue(row, col))}}</div>'
						}, {
							name: '操作',
							width: 150,
							cellTemplate: '<span class="btn-label" ng-click="grid.appScope.setRules(grid, row, row.entity.rules)">验证规则</span>'
						}, {
							name: '唯一性校验',
							width: 150,
							cellTemplate: '<label data-toggle="{on: \'启用\', off: \'停用\'}"><input type="checkbox" ng-model="row.entity.unique"  class="x-chk" ng-true-value="1" ng-false-value="0" ng-click="grid.appScope.setFieldUnique(grid, row, row.entity.unique)" ng-disabled="row.uniqueLoading" /></label>'
						}],
						data: [],
						forceFit: false,
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope;
							_scope.api = api;

							api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
								_scope.query(false);
							});
						}
					},
					query: function(resetPage) {
						var _scope = this;
						if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
							loadModelFieldsData(_scope, _scope.q);
						} else {
							api.gridReset(null, _scope);
						}
					},
					create: function() {
						var _scope = this;
						service.add({
							modelId: id
						}).then(function() {
							_scope.query();
						});
					},
					edit: function() {
						var id = api.getGridSelectedIds(this)
						var _scope = this;
						service.edit(id).then(function() {
							_scope.query();
						});
					},
					add: function() {
						var _$scope = this;
						var loadFieldsData = function(scope, params) {
							scope = scope || this;
							params = params || {};
							angular.extend(params, {
								modelId: id
							});
							return api.gridLoad({
								name: 'meta_fields_filter',
								params: params,
								scope: scope
							});
						};
						api.form({
							title: '添加指标',
							template: require('../views/form_fields.tpl.html'),
							scope: {
								q: {},
								getDataTypeName: service.getDataTypeName,
								getFormTypeName: service.getFormTypeName,
								gridOptions: {
									paginationCurrentPage: api.page.pageNumber,
									paginationPageSize: api.page.pageSize,
									useExternalPagination: true,
									viewportTemplate: '<div class="x-grid-wrap">\
									<div class="x-grid-body">\
										<table cellspacing="0" cellpadding="0">\
											<tbody>\
												<tr ng-repeat="(rowIndex, row) in grid.renderedRows track by $index" ng-class="{\'x-grid-row-selected\':row.isSelected}">\
														<td class="x-grid-group">\
															<table cellspacing="0" cellpadding="0">\
																<tbody>\
																	<tr row="row" index="rowIndex" grid-view-row></tr>\
																</tbody>\
															</table>\
															<div class="x-field-group" ng-if="row.isSelected && grid.getRowValue(row, \'styles\').length > 1">\
																<div class="x-field" ng-repeat="style in grid.getRowValue(row, \'styles\') track by $index" ng-class="{\'active\':row.entity.style==style.id}" ng-click="row.entity.style=style.id">\
																	<div class="x-field-header">\
																		<h4><label><i class="fa" ng-class="{\'fa-dot-circle-o\': row.entity.style==style.id, \'fa-circle-o\': row.entity.style!=style.id}"></i><input type="hidden" name="{{grid.getRowValue(row, \'name\')}}" ng-model="row.entity.style" ng-init="row.entity.style=row.entity.style||grid.getRowValue(row, \'styles\')[0].id" value="{{style.id}}" /> {{style.name}}</label></h4>\
																		<div class="x-field-title">控件类型：{{grid.appScope.getFormTypeName(style.formType)}}</div>\
																	</div>\
																	<div class="x-field-body">\
																		<div class="x-field-items">\
																			<div class="x-field-label" ng-if="style.required">必填</div>\
																			<div class="x-field-label" ng-if="style.display">显示</div>\
																			<div class="x-field-label" ng-if="style.readonly">只读</div>\
																			<div class="x-field-label">默认值：<em>{{style.fieldDefault}}</em></div>\
																			<div class="x-field-label">输入限制长度：<em>{{style.controlsLength}}</em></div>\
																		</div>\
																	</div>\
																</div>\
															</div>\
														</td>\
													</tr>\
												</tbody>\
											</table>\
										</div>\
									</div>',
									columns: [{
										name: '序号',
										width: 50,
										cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
									}, {
										name: '指标名称',
										field: 'metricCode',
										width: 150
									}, {
										name: '显示名称',
										field: 'styleName',
										width: 150
									}, {
										name: '数据类型',
										field: 'fieldType',
										width: 150,
										cellTemplate: '<div class="x-grid-inner">{{grid.appScope.getDataTypeName(grid.getCellValue(row, col))}}</div>'
									}],
									data: [],
									onRegisterApi: function(api, grid) {
										var _scope = grid.appScope;
										_scope.api = api;

										api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
											_scope.query(false);
										});
									}
								},
								query: function(resetPage) {
									var _scope = this;
									if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
										loadFieldsData(_scope, _scope.q);
									} else {
										api.gridReset(null, _scope);
									}
								}
							},
							name: 'meta_model_fields_save',
							data: {
								modelId: id
							},
							beforeSubmit: function(data) {
								var rows = api.getGridSelectedRecords(this);
								if (rows.length === 0) {
									dialog.alert('请选择需要添加的字段！');
									return false;
								}
								data.rows = rows;
							},
							resolveApply: false,
							resolveWait: function() {
								var _scope = this;
								return loadFieldsData(_scope);
							},
							config: {
								size: 680
							}
						}).then(function() {
							_$scope.query();
						});
					},
					remove: function() {
						var _ids = api.getGridSelectedIds(this);
						var _scope = this;
						dialog.confirm('确定要删除选中项？').result.then(function(r) {
							if (r) {
								http.post('meta_model_field_remove', {
									mId: id,
									ids: _ids
								}).then(function() {
									_scope.query(false);
								})
							}
						});
					},
					isFirst: function() {
						var r = api.getGridSelectedRecord(this);
						var data = this.gridOptions.data;
						return data.indexOf(r) === 0;
					},
					isLast: function() {
						var r = api.getGridSelectedRecord(this);
						var data = this.gridOptions.data;
						return data.indexOf(r) === data.length - 1;
					},
					movePrev: function() {
						var _id = api.getGridSelectedId(this);
						var _scope = this;
						http.post({
							name: 'meta_model_field_move_prev',
							params: {
								mId: id,
								id: _id
							}
						}).then(function() {
							_scope.query(false);
						})
					},
					moveNext: function() {
						var _id = api.getGridSelectedId(this);
						var _scope = this;
						http.post({
							name: 'meta_model_field_move_next',
							params: {
								mId: id,
								id: _id
							}
						}).then(function() {
							_scope.query(false);
						})
					},
					hasSelected: function() {
						return api.hasGridSelected(this);
					},
					hasSelectedRecords: function() {
						return api.hasGridSelectedRecords(this);
					}
				},
				resolveApply: false,
				resolveWait: function() {
					var _scope = this;
					return loadModelFieldsData(_scope);
				},
				config: {
					width: '70%'
				}
			});
		}
		$scope.rulesManager = function(ev, id) {
			id = typeof id == 'undefined' ? api.getGridSelectedId($scope) : id;

			var loadModelRulesData = function(scope, params) {
				scope = scope || this;
				params = params || {};
				angular.extend(params, {
					modelId: id
				});
				return api.gridLoad({
					name: 'meta_model_rules',
					params: params,
					scope: scope
				});
			};
			api.form({
				title: '规则管理',
				template: require('../views/form_model_rules.tpl.html'),
				scope: {
					q: {},
					gridOptions: {
						paginationCurrentPage: api.page.pageNumber,
						paginationPageSize: api.page.pageSize,
						useExternalPagination: true,
						columns: [{
							name: '序号',
							width: 50,
							cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
						}, {
							name: '规则名称',
							field: 'ruleName',
							width: 150
						}, {
							name: '描述',
							width: 200,
							field: 'ruleDesc'
						}],
						data: [],
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope;
							_scope.api = api;

							api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
								_scope.query(false);
							});
						}
					},
					query: function(resetPage) {
						var _scope = this;
						if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
							loadModelRulesData(_scope, _scope.q);
						} else {
							api.gridReset(null, _scope);
						}
					},
					create: function() {
						var _scope = this;
						api.form({
							title: '新建规则',
							template: require('../views/form_rule.tpl.html'),
							name: 'meta_rule_add',
							data: {
								ruleType: '2'
							}
						}).then(function() {
							_scope.query();
						});
					},
					add: function() {
						var _$scope = this;
						var loadRulesData = function(scope, params) {
							scope = scope || this;
							params = params || {};
							angular.extend(params, {
								ruleType: 2,
								modelId: id
							});
							return api.gridLoad({
								name: 'meta_rules',
								params: params,
								scope: scope
							});
						};
						api.form({
							title: '添加规则',
							template: require('../views/table_rules.tpl.html'),
							scope: {
								q: {},
								gridOptions: {
									paginationCurrentPage: api.page.pageNumber,
									paginationPageSize: api.page.pageSize,
									useExternalPagination: true,
									columns: [{
										name: '序号',
										width: 50,
										cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
									}, {
										name: '规则名称',
										field: 'ruleName',
										width: 150
									}, {
										name: '描述',
										width: 200,
										field: 'ruleDesc'
									}],
									data: [],
									onRegisterApi: function(api, grid) {
										var _scope = grid.appScope;
										_scope.api = api;

										api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
											_scope.query(false);
										});
									}
								},
								query: function(resetPage) {
									var _scope = this;
									if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
										loadRulesData(_scope, _scope.q);
									} else {
										api.gridReset(null, _scope);
									}
								}
							},
							name: 'meta_model_rules_save',
							data: {
								modelId: id
							},
							beforeSubmit: function(data) {
								var ids = api.getGridSelectedIds(this);
								if (ids.length === 0) {
									dialog.alert('请选择需要添加的规则！');
									return false;
								}
								data.ids = ids;
							},
							resolveApply: false,
							resolveWait: function() {
								var _scope = this;
								return loadRulesData(_scope);
							},
							config: {
								size: 680
							}
						}).then(function() {
							_$scope.query();
						});
					},
					remove: function() {
						var _ids = api.getGridSelectedIds(this);
						var _scope = this;
						dialog.confirm('确定要删除选中项？').result.then(function(r) {
							if (r) {
								http.post('meta_model_rule_remove', {
									mId: id,
									ids: _ids
								}).then(function() {
									_scope.query(false);
								})
							}
						});
					},
					hasSelected: function() {
						return api.hasGridSelected(this);
					},
					hasSelectedRecords: function() {
						return api.hasGridSelectedRecords(this);
					}
				},
				resolveApply: false,
				resolveWait: function() {
					var _scope = this;
					return loadModelRulesData(_scope);
				}
			});
		}

		$scope.hasSelected = function() {
			return api.hasGridSelected($scope);
		}
		$scope.hasSelectedRecords = function() {
			return api.hasGridSelectedRecords($scope);
		}

		query();
	}
}